<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\OlisOrderModel;
use App\Services\Logger;
use App\Services\PayServices;
use Illuminate\Support\Facades\DB;

class OlisOrderDao extends BaseDao
{
    public static function builder_query($params = [])
    {
        $query = OlisOrderModel::query();

        $query->when(checkIsHasField($params,'oli_order_id'),function ($query)use ($params){
            $query->where('oli_order_id',$params['oli_order_id']);
        });

        $query->when(checkIsHasField($params,'order_code'),function ($query)use ($params){
            $query->where('order_code',$params['order_code']);
        });

        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });

        $query->when(checkIsHasField($params,'oli_id'),function ($query)use ($params){
            $query->where('oli_id',$params['oli_id']);
        });

        $query->when(checkIsHasField($params,'status'),function ($query)use ($params){
            $query->where('status',$params['status']);
        });



        return $query->orderByDesc('created_at');
    }


    /**
     * @throws SysExceptions
     */
    public static function add_order($params = [])
    {
        checkForData(
            ['oli_id','pay_type'],
            ['请选择套餐','请选择支付方式'],
            $params
        );
        $order_code = makeOrderNo();
        $oliInfo = OlisDao::builder_query([
            'oli_id'=>$params['oli_id']
        ])->first()->toArray();
        $userInfo = UsersDao::builder_query([
            'user_id'=>$params['user_id']
        ])->first()->toArray();

        //创建订单
        $inser_params = [
            'user_id' => $params['user_id'],
            'oli_id' => $params['oli_id'],
            'order_code' => $order_code,
            'oli_json_data'=>json_encode($oliInfo,JSON_UNESCAPED_UNICODE),
            'price'=>$oliInfo['price'],
            'oli_nums'=>$oliInfo['oli_nums'],
            'vip_index'=>$oliInfo['vip_index'],
            'pay_type'=>$params['pay_type']
        ];

        DB::beginTransaction();
        try {
            //创建订单
            $pay_info = [];
            //余额支付
            if($params['pay_type'] == 2){

                if($userInfo['balance'] < $oliInfo['price']){
                    self::error('余额不足');
                }

                if(!checkIsHasField($params,'pay_pass')){
                    self::error('请输入支付密码');
                }

                if(!password_verify($params['pay_pass'],$userInfo['pay_pass'])){
                    self::error('支付密码不正确');
                }

                $inser_params['status'] =1;
                //扣除金额
                BillsDao::moneyUpdate($inser_params['user_id'],-($inser_params['price']),'购买'.$oliInfo['oli_title'].'扣款');
            }
            self::builder_query()->create($inser_params);
            if($params['pay_type'] == 2){
                self::oli_order_select_data($order_code,1);
            }
            if($params['pay_type'] == 1){
                $pay_info = PayServices::pay([
                    'openid'=>$userInfo['openid'],
                    'order_code'=>$order_code,
                    'price'=>$inser_params['price'],
                    'name'=>$oliInfo['oli_title'],
                    'notify_url'=>route('notice_oli')
                ]);
            }
            DB::commit();
            return $pay_info;
        }catch (\Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }



    public static function noticePay($order_code)
    {
        $query = self::builder_query([
            'order_code'=>$order_code,
            'status'=>0
        ]);
        if(!$query->exists()){
            self::error('不存在');
        }
        $info = $query->first()->toArray();
        DB::beginTransaction();
        try {
            $query->update([
                'status'=>1
            ]);
            //查询状态
            self::oli_order_select_data($order_code,1);
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            Logger::notice_oli('=====>',[
                $exception->getMessage()
            ]);
            self::error($exception->getMessage());
        }
    }


    /**
     * @throws SysExceptions
     */
    public static function oli_order_select_data($order_code = '', $status = 0)
    {
        $query = self::builder_query([
            'order_code'=>$order_code,
            'status'=>$status
        ]);
        if(!$query->exists()){
            self::error('不存在');
        }
        $info = $query->first()->toArray();

        $userInfo = UsersDao::builder_query([
            'user_id'=>$info['user_id']
        ])->first()->toArray();
        //赠送会员
        if($info['vip_index'] == 1){

            //赠送vip
            if($userInfo['vip_index'] == 0){
                UsersDao::builder_query([
                    'user_id'=>$info['user_id']
                ])->update([
                    'vip_index'=>1
                ]);
            }
            //判断上级等级然后奖励成为创客
            if($userInfo['spread_id'] != 0){

                $user_index_count = UsersDao::builder_query([
                    'spread_id'=>$userInfo['spread_id'],
                    'vip_index'=>1
                ])->count();

                //推荐两个及以上
                if($user_index_count >= 2){
                    UsersDao::builder_query([
                        'user_id'=>$userInfo['spread_id']
                    ])->update([
                       'vip_index'=>2
                    ]);
                }

                //这个成为联创
                if($user_index_count >= 12){
                    UsersDao::builder_query([
                        'user_id'=>$userInfo['spread_id']
                    ])->update([
                        'vip_index'=>3
                    ]);
                }
            }
        }

        //判断上级是不是会员(二级返佣消费券)----判断上级等级来奖励
        if($userInfo['spread_id'] != 0){
            $user_spread_info = UsersDao::builder_query([
                'user_id'=>$userInfo['spread_id']
            ])->first()->toArray();
            if($user_spread_info['vip_index'] > 0) {
                //奖励消费券
                ConsumerCouponBillsDao::oli_consumer_coupon_update(
                    $userInfo['spread_id'],
                    15,
                    '下级(' . $userInfo['spread_id'] . ')购买奖励(直推)'
                );

                if($user_spread_info['vip_index'] == 3){
                    ConsumerCouponBillsDao::oli_consumer_coupon_update(
                        $userInfo['spread_id'],
                        3,
                        '下级(' . $userInfo['spread_id'] . ')购买奖励(直推-联创奖励)'
                    );
                }
            }

            if($user_spread_info['spread_id'] != 0){
                $user_two_spread_info = UsersDao::builder_query([
                    'user_id'=>$user_spread_info['spread_id']
                ])->first()->toArray();

                if($user_two_spread_info['vip_index'] > 1) {
                    ConsumerCouponBillsDao::oli_consumer_coupon_update($user_two_spread_info['user_id'],15,'下级'.$userInfo['user_id'].'购买奖励(间推)');
                    if($user_two_spread_info['vip_index'] == 3){
                        ConsumerCouponBillsDao::oli_consumer_coupon_update(
                            $userInfo['spread_id'],
                            3,
                            '下级(' . $userInfo['spread_id'] . ')购买奖励(间推-联创奖励)'
                        );
                    }
                }
            }

        }


        //赠送桶数
        OliBillsDao::oli_nums_update($info['user_id'],$info['oli_nums'],'购买商品获得');

    }

    public static function oli_orders(array $params): array
    {
        $olQuery = self::builder_query(array_merge($params,[
            'status'=>1
        ]));
        return [
            'data'=>$olQuery->get()
        ];
    }

    public static function pageinage(array $all = [])
    {
        return self::builder_query($all)->paginate();
    }
}
